package service.inventory.impl;

import dao.inventory.ItemSupplierDao;
import java.util.List;
import java.util.Map;
import model.inventory.ItemSupplier;
import model.inventory.ItemSupplierId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.inventory.ItemSupplierService;
import utility.NameValueList;
import utility.StringUtils;


@Service("itemSupplierService")
@Transactional(readOnly=true)
public class ItemSupplierServiceImpl implements ItemSupplierService {

    //avoid LazyInitializationException 
    String mainQuery = "select itemSupplier from ItemSupplier itemSupplier "+
            "left join fetch itemSupplier.supplier supplier "+
            "left join fetch itemSupplier.item item";
    
    @Autowired private ItemSupplierDao itemSupplierDao;
    
    @Transactional(readOnly=false)
    @Override
    public boolean save(ItemSupplier data) {
        return itemSupplierDao.save(data);
    }

    @Transactional(readOnly=false)
    @Override
    public boolean delete(ItemSupplier data) {
        return itemSupplierDao.delete(data);
    }

    @Override
    public ItemSupplier get(ItemSupplierId id) {
        String q=mainQuery+" where itemSupplier.id = "+id;
        return itemSupplierDao.getByCustomQuery(q);
    }
    
    @Override
    public ItemSupplier get(int itemId, String kode) {
        String q=mainQuery+" where itemSupplier.id.itemId = "+itemId+
        " and lower(itemSupplier.supplier.kode) = lower("+StringUtils.fmtSQLString(kode)+")";
        return itemSupplierDao.getByCustomQuery(q);
    }
    
    @Override
    public List<ItemSupplier> getAll(int start, int num, Map<NameValueList, Object> params) {
        String query = mainQuery+StringUtils.getFilter(params);
        return itemSupplierDao.getAll(start, num, query);
    }

    @Override
    public List<ItemSupplier> getAll(Map<NameValueList, Object> params) {
        String q=mainQuery+StringUtils.getFilter(params);
        return itemSupplierDao.getAll(q);
    }

    @Override
    public Long count(Map<NameValueList, Object> params) {
        String query= "select count(*) from ItemSupplier itemSupplier "+StringUtils.getFilter(params);
        return itemSupplierDao.count(query);
    }

    @Override
    public Boolean isExist(Map<NameValueList, Object> params) {
        return count(params) > 0 ? true:false;
    }
    
}
